<?php

namespace app\api\model\wanlshop;

use think\Db;
use think\Log;
use think\Exception;
use app\api\model\wanlshop\Order as orderModel;
use app\common\model\User;
use app\common\model\UserFinanceLog;
use think\Model;
use think\model\relation\HasOne;
use traits\model\SoftDelete;

class Order extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'wanlshop_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 订单状态 1=待支付,2=待发货,3=待收货,4=待评论,5=售后订单(已弃用),6=已完成,7=已取消
    public $stateForSpecific = [1, 2, 3, 4, 5, 6, 7];
    // 状态
    public $statusForSpecific = ['normal', 'hidden'];

    // 追加属性
    protected $append = [
        'createtime_text',
        'paymenttime_text',
        'delivertime_text',
        'taketime_text',
        'dealtime_text',
        'state_text',
    ];

    /**
     * 获取订单类型
     * @param $id
     * @return string
     */
    public static function getOrderType($id)
    {
        $data = self::findOrFail($id);
        $type = '';

        //换购订单
        if ($data['score'] > 0) {
            return '积分置换';
        }
        if ($data['coupon_id'] > 0) {
            return '优惠券置换';
        }
        if ($data['invoice_id'] > 0) {
            return '发票抵扣置换';
        }
        if ($data['offline_order'] == 1) {
            return '线下实体店置换';
        }
        if ($data['order_type'] == 1) {
            return '平台旧件置换';
        }
        if ($data['order_type'] == 0) {
            return '普通订单';
        } elseif ($data['order_type'] == 1) {
        } elseif ($data['order_type'] == 2) {
            return '非平台旧件置换';
        }
    }

    protected function setOrderNoAttr($value)
    {
        return substr(time(), -8) . substr(substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $value, -8);
    }

    protected function getStateAttr($value)
    {
        return intval($value);
    }

    public function getStateList()
    {
        return [
            '1' => '待支付',
            '2' => '待发货',
            '3' => '待收货',
            '4' => '待评论',
            '5' => '已退款',
            '6' => '已完成',
            '7' => '已取消',
            '8' => '待审核',
            '9' => '已拒绝',
            '10' => '退款中'
        ];
    }

    public function getStateTextAttr($value, $data)
    {
        $value = $value ?: ($data['state'] ?? '');
        $list = $this->getStateList();
        return $list[$value] ?? '';
    }


    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getPaymenttimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paymenttime']) ? $data['paymenttime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDelivertimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delivertime']) ? $data['delivertime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getTaketimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDealtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['dealtime']) ? $data['dealtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    protected function setPaymenttimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDelivertimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDealtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    // 子订单
    public function orderItem()
    {
        return $this->hasMany('app\api\model\wanlshop\OrderGoods', 'order_id', 'id');
    }

    public function gifts()
    {
        return $this->hasMany(OrderGift::class, 'order_id', 'id');
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    // 店铺
    public function shop()
    {
        return $this->belongsTo('app\api\model\wanlshop\Shop', 'shop_id', 'id', [], 'LEFT');
    }

    // 快递列表
    public function kuaidi()
    {
        return $this->belongsTo('app\api\model\wanlshop\Kuaidi', 'express_name', 'code', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 支付表
     * @return HasOne
     */
    public function pay()
    {
        return $this->hasOne(Pay::class, 'order_id', 'id');
    }

    public static function scoreHandle($oid, $uid)
    {
        $order = self::findOrFail($oid);
        if ($order) {
            $goodsIds = OrderGoods::where(['order_id' => $oid, 'type' => 'new', 'user_id' => $uid])->column('goods_id');
            if ($goodsIds) {
                $integral = Goods::where('id', 'in', $goodsIds)->sum('integral');
                if ($order->score > 0) {
                    $user = User::find($uid);
                    UserFinanceLog::create([
                        'user_id' => $uid,
                        'admin_id' => 0,
                        'type' => 'score',
                        'flag' => 'reduce',
                        'value' => $order->score,
                        'before' => $user->score,
                        'after' => bcsub($user->score, $order->score, 2),
                        'event' => 'pay',
                        'rel_id' => $oid,
                        'remark' => "订单支付:{$order->order_no},积分抵扣:{$order->score}",
                        'status' => 'succeed',
                        'createtime' => time(),
                        'updatetime' => time()
                    ]);
                    $user->score = bcsub($user->score, $order->score, 2);
                    $user->save();
                }
                $user = User::find($uid);
                UserFinanceLog::create([
                    'user_id' => $uid,
                    'admin_id' => 0,
                    'type' => 'score',
                    'flag' => 'add',
                    'value' => $integral,
                    'before' => $user->score,
                    'after' => bcadd($user->score, $integral, 2),
                    'event' => 'pay',
                    'rel_id' => $oid,
                    'remark' => "订单支付:{$order->order_no},下单积分:$integral",
                    'status' => 'succeed',
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
                $user->score = bcadd($user->score, $integral, 2);
                $user->save();
            }
        }
        return true;
    }

    /**
     * 退回换购商品
     * @param $oid
     * @param $uid
     * @return bool|string
     */
    public function returnBuyback($oid, $uid)
    {
        Db::startTrans();
        try {
            $order = orderModel::where(['id' => $oid, 'user_id' => $uid])->find();
            $goods = OrderGoods::where([
                'order_id' => $oid,
                'user_id' => $uid,
                'type' => 'old'
            ])->select();

            //退回换购商品
            OrderGoods::where([
                'id' => ['in', array_column($goods, 'original_goods_id')],
                'order_id' => ['in', array_column($goods, 'original_order_id')],
                'user_id' => $uid,
                'is_buyback' => 1
            ])->update(['is_buyback' => 0]);

            //退回优惠券
            if ($order->coupon_id > 0) {
                (new CouponReceive())->where(['id' => $order->coupon_id, 'user_id' => $uid])->update(['state' => 1]);
            }

            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
    }

    public function realstore()
    {
        return $this->belongsTo(Shop::class, 'real_store_id');
    }
}
